//
//  HostAuthViewController.m
//  penzer
//
//  Created by caiyc on 2018/10/4.
//  Copyright © 2018年 caiyc. All rights reserved.
//

#import "HostAuthViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "AblityViewController.h"
@interface HostAuthViewController ()<UIPickerViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIScrollViewDelegate>
@property(nonatomic,strong)UIImagePickerController *imagePicke;
@property(nonatomic,strong)UIImage *icons;
@property(assign)BOOL idcard;
@property(nonatomic,strong)NSMutableArray *cardArr;
@property(nonatomic,strong)NSMutableArray *xueliArr;
@property(nonatomic,strong)NSMutableArray *cardIdArr;
@property(nonatomic,strong)NSMutableArray *xueliIdArr;
@property(nonatomic,strong)NSString *deleteId;
@property(assign)NSInteger deleIndex;
@property(assign)BOOL iscardedit;
@property(assign)BOOL isxueliedit;
@property(nonatomic,strong)MBProgressHUD *HUD;
@end

@implementation HostAuthViewController
- (IBAction)selectxueli:(UIButton *)sender {
    self.idcard = 0;
    [self PickeImage];
}
- (IBAction)selectIdcard:(UIButton *)sender {
    self.idcard = 1;
    [self PickeImage];
}
//身份证图片视图添加
-(void)addcardImgView{
    for(UIView *view in [self.cardView subviews]){
        if(view!=self.card_Btn){
            [view removeFromSuperview];
            
        }
    }
    NSInteger orginx = self.card_Btn.frame.origin.x+self.card_Btn.frame.size.width+10;
    NSInteger orhinxy = self.card_Btn.frame.origin.y;
    NSInteger imgWidth =80;
    NSInteger imgHeight = 80;
//    NSInteger imgWidth = (screen_width-orginx)/2-30;
//    NSInteger imgHeight = (screen_width-orginx)/2-30;
    for(int i =0;i<self.cardArr.count;i++){
        UIImageView *images = [[UIImageView alloc]initWithFrame:CGRectMake(orginx+100*i, self.card_Btn.center.y-40, imgWidth, imgHeight)];
        if([self.cardArr[i] isKindOfClass:[NSDictionary class]]){
            NSURL *url = [NSURL URLWithString:self.cardArr[i][@"path"]];
                     [images sd_setImageWithURL:url];
        }else{
            images.image = self.cardArr[i];
        }

        [self.cardView addSubview:images];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(orginx+100*i+60, self.card_Btn.center.y-60, 40, 40);
        [btn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        btn.tag = i;
        [btn addTarget:self action:@selector(deleteCardImg:) forControlEvents:UIControlEventTouchUpInside];
        [self.cardView addSubview:btn];
    }
}
-(void)loadInfo{
    NSDictionary *param = @{@"ac":@"member",
                            @"ctrl":@"live_anchor",
                            @"token":[XTool GetDefaultInfo:HOST_USER][@"token"],
                            @"op":@"member",
                            @"ta":@"get_member",
                            };
    [self weqPostHandle:param success:^(id response) {
        if(response){
            if([response[@"data"][@"xueli"]count]>0){
            self.isxueliedit =1;
          //  NSArray *xueliArr = response[@"data"][@"xueli"];
            [self.xueliArr addObjectsFromArray:response[@"data"][@"xueli"]];
            [self addxueliView];
                for(int i =0;i<self.xueliArr.count;i++){
                    [ self.xueliIdArr addObject:self.xueliArr[i][@"id"]];
                }
            }
            if([response[@"data"][@"card"]count]>0){
                self.iscardedit = 1;
                [self.cardArr addObjectsFromArray:response[@"data"][@"card"]];
                for(int i =0;i<self.cardArr.count;i++){
                    [ self.cardIdArr addObject:self.cardArr[i][@"id"]];
                }
                [self addcardImgView];
            }
        }
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)addxueliView{
    for(UIView *view in [self.xueliView subviews]){
        if(view!=self.xueli_Btn){
            [view removeFromSuperview];
            
        }
    }
    NSInteger orginx = self.xueli_Btn.frame.origin.x+self.xueli_Btn.frame.size.width+10;
    NSInteger orhinxy = self.xueli_Btn.frame.origin.y;
    NSInteger imgWidth =80;
    NSInteger imgHeight = 80;
     for(int i =0;i<self.xueliArr.count;i++){
        UIImageView *images = [[UIImageView alloc]initWithFrame:CGRectMake(orginx+100*i, self.card_Btn.center.y-40, imgWidth, imgHeight)];
         if([self.xueliArr[i] isKindOfClass:[NSDictionary class]]){
            NSURL *url = [NSURL URLWithString:self.xueliArr[i][@"path"]];
            [images sd_setImageWithURL:url];
        }else{
            images.image = self.xueliArr[i];
        }

        [self.xueliView addSubview:images];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(orginx+100*i+60, self.card_Btn.center.y-60, 40, 40);
        [btn setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        btn.tag = i;
        [btn addTarget:self action:@selector(delectxueliImg:) forControlEvents:UIControlEventTouchUpInside];
        [self.xueliView addSubview:btn];
    }
}
-(void)deleteCardImg:(UIButton *)sender{
    self.idcard = 1;

    self.deleteId = self.cardIdArr[sender.tag];

    [self deleImgFromSevice];
}
-(void)delectxueliImg:(UIButton *)sender{
      self.idcard = 0;
    self.deleteId = self.xueliIdArr[sender.tag];

     [self deleImgFromSevice];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    if(self.idcard==1){
        if(self.cardArr.count==2){
            [WToast showWithText:@"只需两张照片，谢谢"];
             [self.imagePicke dismissViewControllerAnimated:YES completion:nil];
            return;
        }
        [self.cardArr addObject:image];
        [self addcardImgView];
    }else{
        if(self.xueliArr.count==2){
            [WToast showWithText:@"只需两张照片，谢谢"];
             [self.imagePicke dismissViewControllerAnimated:YES completion:nil];
            return;
        }
        [self.xueliArr addObject:image];
        [self addxueliView];
    }
//    self.icon_Img.image = image;
    self.icons = image;
    [self uploadImg];
    [self.imagePicke dismissViewControllerAnimated:YES completion:nil];
    
    
    
    
}
-(void)deleImgFromSevice{
    NSDictionary *param = @{@"ac":@"member",
                            @"ctrl":@"live_anchor",
                            @"token":[XTool GetDefaultInfo:HOST_USER][@"token"],
                            @"op":@"member",
                            @"ta":@"anchor_picdel",
                            @"id":self.deleteId};
    [self weqPostHandle:param success:^(id response) {
        if(response){
            if(self.idcard==1){
                [self.cardIdArr removeObject:self.deleteId];
              //  [self.cardIdArr removeObjectAtIndex:self.deleIndex];
                [self.cardArr removeObjectAtIndex:self.deleIndex];
                [self addcardImgView];
            }else{
                [self.xueliIdArr removeObject:self.deleteId];
                [self.xueliArr removeObjectAtIndex:self.deleIndex];
                [self addxueliView];
            }
        }
    } failure:^(NSError *error) {
        
    }];
}
-(void)uploadImg{
    NSString *pic_type = @"card";
    if(self.idcard==0){
        pic_type= @"xueli";
    }
    self.HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:_HUD];
    _HUD.label.text = @"自动上传图片中";
    //细节文字
    _HUD.detailsLabel.text = @"请耐心等待";
    //显示对话框
    [_HUD showAnimated:YES];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"text/html", nil]];
    NSDictionary *paramter = @{@"c":@"entry",@"i":@"10",@"ac":@"member",@"ctrl":@"live_anchor",@"token":[XTool GetDefaultInfo:HOST_USER][@"token"],@"op":@"member",@"m":@"bz_activities",@"ta":@"anchor_pic",@"pic_type":pic_type};
    
    NSLog(@"发布参数：%@",paramter);
    
    [manager POST:BASE_URL parameters:paramter constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //        for(NSInteger i = 0; i < self.image_Array.count; i++) {
        if(self.icons){
            NSData * imageData = UIImageJPEGRepresentation(self.icons, 0.5);
            // 上传的参数名
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
            //}
        }
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSLog(@"上传回调===%@",responseObject);
        [self.HUD removeFromSuperview];
        if([[responseObject objectForKey:@"message"][@"resultCode"]integerValue]==0)
        {
           // [WToast showWithText:@"修改成功"];
            if(self.idcard==1){
                NSString *ids = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"message"][@"data"]];
                [self.cardIdArr addObject:ids];
            }else{
                NSString *ids = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"message"][@"data"]];
                [self.xueliIdArr addObject:ids];
            }
           
        }
        else{
            [WToast showWithText:responseObject[@"message"][@"resultMessage"]];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [WToast showWithText:@"更改失败请重试"];
        [self.HUD removeFromSuperview];
       
    }];
}
-(void)PickeImage{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"相机" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            [WToast showWithText:@"相机功能受限，请检查"];
        }
        else
        {
            NSString * mediaType = AVMediaTypeVideo;
            AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
            if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
            {
                [WToast showWithText:@"相机没权限，请在设置里面打开"];
                //没权限
                return ;
            }
            else if(!self.imagePicke)
            {
                self.imagePicke = [[UIImagePickerController alloc]init];
                self.imagePicke.sourceType = UIImagePickerControllerSourceTypeCamera;
                self.imagePicke.delegate = self;
                [self presentViewController:self.imagePicke animated:YES completion:nil];
            }
            else
            {
                self.imagePicke.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:self.imagePicke animated:YES completion:nil];
            }
        }
        
        
    }];
    UIAlertAction *libra = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString * mediaType = AVMediaTypeVideo;
        AVAuthorizationStatus  authorizationStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
        if (authorizationStatus == AVAuthorizationStatusRestricted|| authorizationStatus == AVAuthorizationStatusDenied)
        {
            [WToast showWithText:@"相机没权限，请在设置里面打开"];
            return ;
        }
        
        
        if(self.imagePicke)
        {
            self.imagePicke.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        }
        else
        {
            self.imagePicke = [[UIImagePickerController alloc]init];
            self.imagePicke.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            self.imagePicke.delegate = self;
        }
        [self presentViewController:self.imagePicke animated:YES completion:nil];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [self presentViewController:alert animated:YES completion:nil];
    [alert addAction:camera];
    [alert addAction:libra];
    [alert addAction:cancel];
}
- (void)viewDidLoad {
    [super viewDidLoad];
      [self setNavigation:1 andTitle:@"身份认证" andNaviColor:[UIColor whiteColor] andTitleColor:nil];
    self.cardArr = [NSMutableArray array];
    self.xueliArr = [NSMutableArray array];
    self.cardIdArr = [NSMutableArray array];
    self.xueliIdArr = [NSMutableArray array];
    
    [self loadInfo];
    // Do any additional setup after loading the view from its nib.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)Next_Action:(id)sender {
    AblityViewController *vc = [[AblityViewController alloc]init];
    [self pushSecondVC:vc];
}
@end
